/*
 * @(#)OpenAction.java  2.0.1  2006-05-18
 *
 * Copyright (c) 2005-2006 Werner Randelshofer
 * Staldenmattweg 2, Immensee, CH-6405, Switzerland.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * Werner Randelshofer. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with Werner Randelshofer.
 */

package umage.core;

import org.jhotdraw.xml.DefaultDOMFactory;
import org.jhotdraw.xml.NanoXMLLiteDOMInput;

import java.awt.event.*;
import javax.swing.*;

import java.io.*;

import org.jhotdraw.app.Application;
import org.jhotdraw.app.Project;
import org.jhotdraw.app.action.OpenAction;


/**
 * Opens a file in new project, or in the current project, if it is empty.
 *
 * @author  Werner Randelshofer
 * @version 2.0.1 2006-05-18 Print stack trace added.
 * <br>2.0 2006-02-16 Support for preferences added.
 * <br>1.0.1 2005-07-14 Make project explicitly visible after creating it.
 * <br>1.0  04 January 2005  Created.
 */
public class MultiOpenAction extends OpenAction {
    protected JFileChooser fileChooser;
    
    /** Creates a new instance. */
    public MultiOpenAction(Application app) {
        super(app);
        fileChooser = new JFileChooser(System.getProperty("user.home"));
    }
    
    public void actionPerformed(ActionEvent evt) {
        final Application app = getApplication();
        if (app.isEnabled()) {
        	app.setEnabled(false);
            if (fileChooser.showOpenDialog(app.getComponent()) == JFileChooser.APPROVE_OPTION) {
            	File file = fileChooser.getSelectedFile();
            	if (file == null || !determineSelectedProject(file)) {
            		app.setEnabled(true);
            		return;
            	}
            	Project p = app.createProject();
            	app.add(p);
                app.show(p);
                openFile(fileChooser, p);
            } else {
                app.setEnabled(true);
            }
        }
    }
    
    protected boolean determineSelectedProject(File file) {
    	InputStream in = null;
    	try {
    		if (file == null) return false;
    		in = new BufferedInputStream(new FileInputStream(file));
    		NanoXMLLiteDOMInput domi = new NanoXMLLiteDOMInput(new DefaultDOMFactory(), in);
    		domi.openElement(0);
    		String projectClass = domi.getTagName();
    		domi.closeElement();
    		UMageApplicationModel model = (UMageApplicationModel) getApplication().getModel();
    		model.setProjectClass(Class.forName("umage.projects." + projectClass));
    		return true;
    	} catch (Exception ex) {
    		ex.printStackTrace();
    		return false;
    	} finally {
    		if (in != null) try { in.close(); } catch (IOException e) {};
    	}
    }
}